package top.swimmer.concurrent.thread;

/**
 * BLOCKED, WAITING
 */
public class AllStates {
    private static Thread[] threads = new Thread[2];

    private static Thread.State[] states = new Thread.State[2];

    public static void main(String[] args) {
        Thread thread_1 = newThread("thread_1", 1);
        Thread thread_2 = newThread("thread_2", 10);
        threads[0] = thread_1;
        threads[1] = thread_2;

        states[0] = thread_1.getState();
        states[1] = thread_2.getState();

        thread_1.start();
        thread_2.start();

        try {
            Thread.sleep(1L);
            writeThreadStatus();
            Thread.sleep(300L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        writeThreadStatus();

        boolean flag = false;

        for (;;) {
            if (!threads[0].isAlive() && threads[1].isAlive() && !flag) {
                System.out.println("thread_1: dead");
                flag = true;
                writeThreadStatus();
            }
            if (threads[0].isAlive() && !threads[1].isAlive() && !flag) {
                System.out.println("thread_2: dead");
                flag = true;
                writeThreadStatus();
            }
            if (!threads[0].isAlive() && !threads[1].isAlive()) {
                System.out.println("all: dead");
                writeThreadStatus();
                break;
            }
        }
    }

    private static Thread newThread(String name, int priority) {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                go();
            }
        }, name);

        thread.setPriority(priority);

        return thread;
    }

    private static void writeThreadStatus() {
        System.out.println("********************************");
        System.out.println("原状态: ");
        System.out.println(threads[0].getName() + ": " + states[0]);
        System.out.println(threads[1].getName() + ": " + states[1]);
        System.out.println("现状态: ");
        states[0] = threads[0].getState();
        states[1] = threads[1].getState();
        System.out.println(threads[0].getName() + ": " + states[0]);
        System.out.println(threads[1].getName() + ": " + states[1]);
        System.out.println("********************************");
    }

    private static synchronized void go() {
        for (int i = 0; i < 100000000; i++) {
            i++;
            i--;
            if (i % 8000000 == 0) {
                try {
                    Thread.sleep(300L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
